package com.tbsoft.ehr.dao.pubField;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tbsoft.ehr.model.PublicField;

public class PubFieldDaoImpl extends HibernateDaoSupport implements PubFieldDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<PublicField> getPubFieldByType(final String type) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
		
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query q= session.createQuery("from PublicField pf where pf.fieldType=?");
				q.setString(0, type);
				return q.list();
			}
		});
	}

	@Override
	public List<PublicField> getPubFields() {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
		
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				// TODO Auto-generated method stub
				return session.createQuery("from PublicField pf").list();
			}
		});
	}

	@Override
	public void save(PublicField pf) {
		getHibernateTemplate().save(pf);
	}

	@Override
	public List<String> getPubFieldTypes() {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
		
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query q = session.createSQLQuery("select distinct FIELD_TYPE from EHR_PUBLIC_FIELD");
				return q.list();
			}
		});
	}

	@Override
	public Map<String, String> getPubFieldTypeMap() {
		List<Object[]> objLst =  getHibernateTemplate().executeFind(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query q = session.createSQLQuery("select distinct FIELD_TYPE,FIELD_REMARK from EHR_PUBLIC_FIELD");
				return q.list();
			}
		});
		Map<String,String> pubTypMap = new HashMap<String,String>();
		if(objLst.size()>0){
			for(Object[] objArr:objLst){
				pubTypMap.put(objArr[0].toString(), objArr[1].toString());
			}
		}
		return pubTypMap;
	}

	@Override
	public void delete(PublicField pf) {
		getHibernateTemplate().delete(pf);
	}

	@Override
	public PublicField getPubField(PublicField pf) {
		return (PublicField)getHibernateTemplate().get(PublicField.class, pf.getId());
	}

	@Override
	public void update(PublicField pf) {
		getHibernateTemplate().update(pf);
	}

}
